/**
 * 复位地图
 */

import * as turf from '@turf/turf'

/**
 * 整体复位 / 根据所给图层复位
 * 基于所有 / 部分 可视图层包围盒复位
 */
export function gisMapResetByVisibleLayers(
  mapboxInstance: any,
  layers: any,
  layerData: any
) {
  let fitBounds: any = [
    [73.536163, 53.558094],
    [135.084259, 7.397329],
  ]
  if (layers.length >= 1) {
    const layerBounds: any[] = []
    layers.forEach((layer: any) => {
      const currentLayerData: any = layerData[layer.id]
      if (currentLayerData) {
        const [minX, minY, maxX, maxY] = turf.bbox(currentLayerData.geojson)
        // 做标合法
        if (
          Math.abs(minX) <= 180 &&
          Math.abs(minY) <= 90 &&
          Math.abs(maxX) <= 180 &&
          Math.abs(maxY) <= 90
        ) {
          layerBounds.push([minX, minY])
          layerBounds.push([maxX, maxY])
        }
      }
    })
    if (layerBounds.length >= 2) {
      // @ts-ignore
      fitBounds = turf.bbox(turf.lineString(layerBounds))
    }
  }
  try {
    mapboxInstance.fitBounds(fitBounds, { padding: 50 })
  } catch (error) {
    console.log(error)
  }
}

/**
 * 根据单一图层复位
 * @param mapboxInstance
 * @param layerId
 * @param layerData
 */
export function gisMapResetByLayer(
  mapboxInstance: any,
  layerId: number,
  layerData: any
) {
  const currentLayerData: any = layerData[layerId]
  const fitBounds: any[] = turf.bbox(currentLayerData.geojson)
  mapboxInstance.fitBounds(fitBounds, { padding: 50 })
}
